/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.service;

import br.com.foxline.model.Enterprise;
import br.com.foxline.model.Lot;
import br.com.foxline.model.Message;
import br.com.foxline.model.Users;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.faces.context.FacesContext;
import javax.persistence.Query;

/**
 *
 * @author luciano
 */
@Stateless
public class MessageService extends GenericService<Message> {

    public MessageService() {
        super(Message.class);
    }
    
    @Override
    public void save(Message message){
        message.setDateMessage(new Date());
        super.save(message);
    }

   @EJB
   UserService userService;

    public List<Message> messages() {
        List<Message> messages = new ArrayList<Message>();
        try {
            String sql = "Select m from Message m JOIN m.userTo u where u.login=:login order by m.dateMessage DESC";
            Query query = getEntityManager().createQuery(sql).setMaxResults(50);
            query.setParameter("login", userService.getCurrentUser());
            messages = query.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messages;
    }
    
    /**
     * Retorna a Quantidade de Mensagens não lidas do usuário logado.
     * @return 
     */
    public int countMessagesUnread(){
        Long i = new Long(0);
        try {
            String sql = "Select COUNT(m) from Message m JOIN m.userTo u where u.login=:login AND m.wasRead=FALSE";
            Query query = getEntityManager().createQuery(sql);
            query.setParameter("login", userService.getCurrentUser());
            i = (Long) query.getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i.intValue();
    }
    
}
